package com.zxbit.flash.ui.activity.login;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.text.SpannableString;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.zxbit.flash.R;
import com.zxbit.flash.base.BaseTitleActivity;
import com.zxbit.flash.common.Constant;
import com.zxbit.flash.common.RouterMap;
import com.zxbit.flash.mvpview.RegisterMvpView;
import com.zxbit.flash.mvpview.VerifyCodeMvpView;
import com.zxbit.flash.presenter.RegisterPresenter;
import com.zxbit.flash.presenter.VerifyCodePresenter;
import com.zxbit.flash.response.BlankResponse;
import com.zxbit.flash.utils.StringUtils;
import com.zxbit.flash.utils.ToastUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

@SuppressLint("CheckResult")
@Route(name = "忘记密码", path = RouterMap.FIND_PASSWORD_PAGE)
public class RetrievePswAcrivity extends BaseTitleActivity implements RegisterMvpView, VerifyCodeMvpView {

    @BindView(R.id.phone_numer_text)
    EditText phoneNumerText; // 手机号
    @BindView(R.id.verify_code_text)
    EditText verifyCodeText; // 验证码
    @BindView(R.id.password_text)
    EditText passwordText; // 密码
    @BindView(R.id.do_acquire_verify_code)
    Button doAcquireVerifyCode; // 短信验证
    @BindView(R.id.show_psw_text)
    CheckBox showPswText;
    @BindView(R.id.confirm_btn)
    Button btnConfirm; // 确定按钮

    private RegisterPresenter registerPresenter;
    private VerifyCodePresenter verifyCodePresenter;
    private boolean isStartCountDown;
    private CustomerCountDownTimer countDownTimer;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        passwordText.setTransformationMethod(PasswordTransformationMethod.getInstance());
    }

    @Override
    protected void onUIReady() {
        registerPresenter = new RegisterPresenter(this);
        verifyCodePresenter = new VerifyCodePresenter(this);
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_retrieve_psw;
    }

    @OnClick({R.id.confirm_btn, R.id.do_acquire_verify_code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.do_acquire_verify_code:
                if (isStartCountDown) return;
                getVerifyCode();
                break;
            case R.id.confirm_btn:
                String verifyMsg = checkUpdatePswParams();
                if (!StringUtils.isEmpty(verifyMsg)) {
                    ToastUtils.showShort(this, verifyMsg);
                    return;
                }
                registerPresenter.registerRequest(phoneNumerText.getText().toString().trim(),
                        verifyCodeText.getText().toString().trim(),
                        passwordText.getText().toString().trim(), "2");
                showLoadingView();
                break;
        }
    }

    @OnCheckedChanged(R.id.show_psw_text)
    public void OnCheckedChanged(boolean isChecked) {
        if (isChecked) {
            passwordText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            passwordText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }

    private void getVerifyCode() {
        String phoneNum = phoneNumerText.getText().toString();
        if (StringUtils.isEmpty(phoneNum)) {
            ToastUtils.showShort(this, getStringResource(R.string.register_user_name_is_null));
            return;
        }
        verifyCodePresenter.getVoiceCode(phoneNum, 1);
        showLoadingView();
    }

    private String checkUpdatePswParams() {
        if (phoneNumerText == null || phoneNumerText.getText() == null || StringUtils.isEmpty(phoneNumerText.getText().toString())) {
            return getStringResource(R.string.register_user_name_is_null);
        }
        if (verifyCodeText == null || verifyCodeText.getText() == null || StringUtils.isEmpty(verifyCodeText.getText().toString())) {
            return getStringResource(R.string.register_verify_code_is_null);
        }
        if (passwordText == null || passwordText.getText() == null || StringUtils.isEmpty(passwordText.getText().toString())) {
            return getStringResource(R.string.register_psw_is_null);
        }
        return null;
    }

    @Override
    public void onGetDataNext(BlankResponse response) {
        if (response.getStatus() == Constant.HTTP_OK) {
            ToastUtils.showShort(RetrievePswAcrivity.this, getStringResource(R.string.find_password_suc_and_go_to_login));
            ARouter.getInstance().build(RouterMap.LOGIN_PAGE)
                    .withString(Constant.USER_NAME, phoneNumerText.getText().toString().trim()).navigation();
        } else {
            ToastUtils.showShort(RetrievePswAcrivity.this, getResources().getString(R.string.find_password_failed));
        }
    }

    @Override
    public void onGetDataNext(String phoneNum) {
    }

    @Override
    public void onGetDataNext(BlankResponse response, int type) {
        dismissLoadingView();
        if (response.getStatus() == Constant.HTTP_OK) {
            processCountDownView(doAcquireVerifyCode,
                    new SpannableString(getStringResource(R.string.register_acquire_verity_code)));
        } else {
            ToastUtils.showShort(RetrievePswAcrivity.this, getStringResource(R.string.register_acquire_code_failed));
        }
    }

    @Override
    public void onGetDataError(Throwable throwable) {
        dismissLoadingView();
    }

    private class CustomerCountDownTimer extends CountDownTimer {
        private TextView textView;
        private Drawable background;
        private SpannableString endStrRes;

        public void updateTextView(TextView textView, SpannableString strSpan) {
            this.textView = textView;
            this.endStrRes = strSpan;
            background = this.textView.getBackground();

        }

        public CustomerCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (this.textView == null) return;
            textView.setText((millisUntilFinished / 1000 + 1) + "s");
        }

        @Override
        public void onFinish() {
            if (this.textView == null) return;
            isStartCountDown = false;
            if (background != null) {
                this.textView.setBackground(background);
            }
            if (this.endStrRes != null) {
                this.textView.setText(endStrRes);
            }
            textView.setEnabled(true);
        }
    }

    /**
     * 处理倒计时view
     */
    private void processCountDownView(final TextView countDownView, final SpannableString stringSpan) {
        isStartCountDown = true;
        if (countDownTimer == null) {
            countDownTimer = new CustomerCountDownTimer(59 * 1000, 1000);
        } else {
            countDownTimer.cancel();
        }
        countDownTimer.updateTextView(countDownView, stringSpan);
        countDownView.setEnabled(false);

        countDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}
